package src.com.hpu.callback;

import java.io.IOException;

import com.hpu.bean.NoticeFile;
import com.hpu.constants.HttpConstants;

import android.os.Handler;
import android.os.Message;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 实现了下载业务类的回调接口
 * @author Administrator
 *
 */
public class DownloadCallback implements Callback {

	private Handler handler;

	public DownloadCallback(Handler handler) {
		this.handler = handler;
	}

	@Override
	public void onFailure(Call arg0, IOException arg1) {
		handler.sendEmptyMessage(HttpConstants.DOWNLOAD_ERROR);
	}

	@Override
	public void onResponse(Call arg0, Response response) throws IOException {
		String fileName = response.header("Content-Disposition");
		byte[] bytes = response.body().bytes();
		String value = new String(bytes);
		System.out.println("filename:"+fileName+","+value);
		if(value.equals("404")){
			handler.sendEmptyMessage(HttpConstants.VPN_TOOLONG);
		}
		else if(value.equals("501")){
			handler.sendEmptyMessage(HttpConstants.KEY_ERROR);
		}
		else if(value.equals("502")){
			handler.sendEmptyMessage(HttpConstants.NEED_INFO);
		}
		else if(value.equals("400")||fileName == null || fileName.indexOf("=") == -1){
			handler.sendEmptyMessage(HttpConstants.DOWNLOAD_ERROR);
		}
		else {
			fileName = fileName.substring(fileName.indexOf("=") + 1);
			Message message = new Message();
			message.what = HttpConstants.DOWNLOAD_SUCCESS;
			message.obj = new NoticeFile(fileName,bytes);
			handler.sendMessage(message);
		}
		response.close();
		response.body().close();
	}

}
